#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define MAX_BUFFER_SIZE 1024

int main() {
    int sock = 0, valread;
    struct sockaddr_in serv_addr;
    char buffer[MAX_BUFFER_SIZE] = {0};
    const char *message = "Hello from Client";

    // 创建套接字
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation failed");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(8080);

    // 将IP地址从字符串转换为网络字节序
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
        perror("Invalid address/Address not supported");
        return -1;
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("Connection Failed");
        return -1;
    }

    // 发送消息到服务器
    // send(sock, message, strlen(message), 0 );
    sendto(sock, message, strlen(message), 0, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));
    printf("Hello message sent\n");

    // 接收服务器响应
    socklen_t len = sizeof(serv_addr);
    valread = recvfrom(sock, (char *)buffer, MAX_BUFFER_SIZE, 0, (struct sockaddr *)&serv_addr, &len);
    printf("receiver from server: %s\n", buffer );

    close(sock); // 关闭套接字

    return 0;
}